﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Web;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace Common
{
    public class WorkTool
    {
        #region 文档操作

        /// <summary>
        /// 保存上传的文件
        /// </summary>
        /// <param name="FileNamePrefix">文件名前缀（可为空）</param>
        /// <param name="MaxFileSize">单个最大允许的文件字节数</param>
        /// <param name="filekey">File控件的Key(即Name属性)</param>
        /// <param name="attachSave">//附件保存方式  0=默认方式直接存入 1=按年/月/日存入不同目录 2=按年/月/存入不同目录</param>
        /// <param name="UploadDir">上传的文件目录</param>
        /// <param name="quality">是否是高质量图片 取值范围0--100</param>
        /// <returns>上传成功返回文件名，否则返回为空</returns>
        public static string SaveRequestFiles(string FileNamePrefix, int MaxFileSize, string filekey, string UploadDir, int attachSave)
        {
            return SaveRequestFiles(FileNamePrefix, MaxFileSize, filekey, UploadDir, attachSave, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
        }
        
        /// <summary>
        /// 保存上传的文件
        /// </summary>
        /// <param name="FileNamePrefix">文件名前缀（可为空）</param>
        /// <param name="MaxFileSize">单个最大允许的文件字节数</param>
        /// <param name="filekey">File控件的Key(即Name属性)</param>
        /// <param name="attachSave">//附件保存方式  0=默认方式直接存入 1=按年/月/日存入不同目录 2=按年/月/存入不同目录</param>
        /// <param name="UploadDir">上传的文件目录</param>
        /// <param name="quality">是否是高质量图片 取值范围0--100</param>
        /// <param name="pPartStartPointX">0</param>
        /// <param name="pPartStartPointY">0</param>
        /// <param name="pPartWidth">截取框的宽</param>
        /// <param name="pPartHeight">截取框的高</param>
        /// <param name="pOrigStartPointX">距离左边</param>
        /// <param name="pOrigStartPointY">距离顶边</param>
        /// <param name="imageWidth">实际宽度</param>
        /// <param name="imageHeight">实际高度</param>
        /// <param name="smallHeight">缩略图高度</param>
        /// <param name="smallWidth">缩略图宽度</param>
        /// <returns>上传成功返回文件名，否则返回为空</returns>
        public static string SaveRequestFiles(string FileNamePrefix, int MaxFileSize, string filekey, string UploadDir, int attachSave, int pPartStartPointX, int pPartStartPointY, int pPartWidth, int pPartHeight, int pOrigStartPointX, int pOrigStartPointY, int imageWidth, int imageHeight, int smallWidth, int smallHeight)
        {
            string result = "";

            int fCount = HttpContext.Current.Request.Files.Count;
            for (int i = 0; i < fCount; i++)
            {
                if (!HttpContext.Current.Request.Files[i].FileName.Equals("") && HttpContext.Current.Request.Files.AllKeys[i].Equals(filekey))
                {
                    string filename = Path.GetFileName(HttpContext.Current.Request.Files[i].FileName);//文件名
                    string fileextname = CommUtils.CutString(filename, filename.LastIndexOf(".") + 1).ToLower();//扩展名
                    string filetype = HttpContext.Current.Request.Files[i].ContentType.ToLower();//文件类型
                    int filesize = HttpContext.Current.Request.Files[i].ContentLength;//文件大小                    

                    //判断文件类型是否符合要求
                    if (!string.IsNullOrEmpty(filename) && CommUtils.IsImgFilename(filename))
                    {
                        //限定上传文件大小
                        if (MaxFileSize >= filesize)
                        {
                            string saveDir = "";
                            if (attachSave == 1) saveDir = DateTime.Now.ToString("yyyy") + DateTime.Now.ToString("MM") + DateTime.Now.ToString("dd");
                            if (attachSave == 2) saveDir = DateTime.Now.ToString("yyyy") + DateTime.Now.ToString("MM");

                            if (!string.IsNullOrEmpty(saveDir)) saveDir += "\\";
                            if (!Directory.Exists(UploadDir + saveDir)) CommUtils.CreateDir(UploadDir + saveDir);   // 如果指定目录不存在则建立

                            //根据年月日时分秒+随机数产生新文件名
                            long tick = DateTime.Now.Ticks;
                            Random random = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32));
                            string newFileName = FileNamePrefix + DateTime.Now.ToString("dd") + DateTime.Now.ToString("hh") + DateTime.Now.ToString("mm") + DateTime.Now.ToString("ss") + random.Next(1000, 9999).ToString() + "." + fileextname;

                            Image img = Image.FromStream(HttpContext.Current.Request.Files[i].InputStream);
                            if (img == null) continue;
                            result = SaveRequestFiles(img, fileextname, UploadDir, saveDir, newFileName, pPartStartPointX, pPartStartPointY, pPartWidth, pPartHeight, pOrigStartPointX, pOrigStartPointY, imageWidth, imageHeight, smallWidth, smallHeight);
                        }
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 保存上传的文件
        /// </summary>
        /// <param name="img"></param>
        /// <param name="fileextname"></param>
        /// <param name="UploadDir">上传的文件目录</param>
        /// <param name="saveDir"></param>
        /// <param name="newFileName"></param>
        /// <param name="pPartStartPointX"></param>
        /// <param name="pPartStartPointY"></param>
        /// <param name="pPartWidth">截取框的宽</param>
        /// <param name="pPartHeight">截取框的高</param>
        /// <param name="pOrigStartPointX">距离左边</param>
        /// <param name="pOrigStartPointY">距离顶边</param>
        /// <param name="imageWidth"></param>
        /// <param name="imageHeight"></param>
        /// <param name="smallWidth">缩略图高度</param>
        /// <param name="smallHeight">缩略图宽度</param>
        /// <returns></returns>
        public static string SaveRequestFiles(Image img, string fileextname, string UploadDir, string saveDir, string newFileName, int pPartStartPointX, int pPartStartPointY, int pPartWidth, int pPartHeight, int pOrigStartPointX, int pOrigStartPointY, int imageWidth, int imageHeight, int smallWidth, int smallHeight)
        {
            string result = "";

            //未指定缩略图大小时，当图片过大则生成缩略图
            if (smallWidth == 0 && smallHeight == 0)
            {
                if (img.Width > 480)
                {
                    smallWidth = 480;
                    smallHeight = Convert.ToInt32(img.Height * (Convert.ToSingle(480) / img.Width));
                }
                if ((img.Height > 480 && smallHeight == 0) || smallHeight > 480)
                {
                    smallHeight = 480;
                    smallWidth = Convert.ToInt32(img.Width * (Convert.ToSingle(480) / img.Height));
                }
            }

            if (smallWidth != 0 || smallHeight != 0)
            {
                try
                {
                    Bitmap bmpimg = new Bitmap(smallWidth, smallHeight);
                    Graphics gdiobj = Graphics.FromImage(bmpimg);

                    if (pPartWidth > 0 || pPartHeight > 0)
                    {
                        Rectangle destRect = new Rectangle(new Point(pPartStartPointX, pPartStartPointY), new Size(smallWidth, smallHeight));//目标位置
                        Rectangle origRect = new Rectangle(new Point(pOrigStartPointX, pOrigStartPointY), new Size(pPartWidth, pPartHeight));//原图位置（默认从原图中截取的图片大小等于目标图片的大小）
                        //设置高质量插值法
                        gdiobj.InterpolationMode = InterpolationMode.High;
                        //设置高质量,低速度呈现平滑程度
                        gdiobj.SmoothingMode = SmoothingMode.HighQuality;
                        //清空画布并以透明背景色填充
                        gdiobj.Clear(Color.White);
                        gdiobj.DrawImage(img, destRect, origRect, GraphicsUnit.Pixel);
                    }
                    else
                    {
                        gdiobj.DrawImage(img, 0, 0, smallWidth, smallHeight);
                    }
                    img = bmpimg;
                }
                catch
                {
                }
            }


            try
            {
                img.Save(UploadDir + saveDir + newFileName);
            }
            catch
            {
            }
            if (!string.IsNullOrEmpty(result)) result += "|";
            result += saveDir + newFileName;
            img.Dispose();

            return result;
        }

        /// <summary>
        /// 多文档上传
        /// </summary>
        /// <param name="FileNamePrefix">文件名前缀（可为空）</param>
        /// <param name="MaxFileSize">单个最大允许的文件字节数</param>
        /// <param name="filekey">File控件的Key(即Name属性)</param>
        /// <param name="UploadDir">上传的文件目录</param>
        /// <param name="attachSave">//文件保存方式  0=默认方式直接存入 1=按年/月/日存入不同目录 2=按年/月/存入不同目录</param>
        /// <param name="AFileSize"></param>
        /// <param name="ErrorStr">失败的信息</param>
        /// <param name="SuccessStr">成功的信息</param>
        /// <returns></returns>
        public static bool SaveRequestFiles(string FileNamePrefix, int MaxFileSize, string filekey, string UploadDir, int attachSave, bool isOffice, out string AFileSize, out string ErrorStr, out string SuccessStr, out string sFileName, out string sSaveDir)
        {
            bool result = false;

            int fCount = HttpContext.Current.Request.Files.Count;
            ErrorStr = "";
            SuccessStr = "";
            sFileName = "";
            sSaveDir = "";
            AFileSize = "";
            for (int i = 0; i < fCount; i++)
            {
                if (!HttpContext.Current.Request.Files[i].FileName.Equals("") && HttpContext.Current.Request.Files.AllKeys[i].Equals(filekey))
                {
                    string filename = Path.GetFileName(HttpContext.Current.Request.Files[i].FileName);//文件名
                    string fileextname = CommUtils.CutString(filename, filename.LastIndexOf(".") + 1).ToLower();//扩展名
                    string filetype = HttpContext.Current.Request.Files[i].ContentType.ToLower();//文件类型
                    int filesize = HttpContext.Current.Request.Files[i].ContentLength;//文件大小

                    if (isOffice)
                    {
                        if (fileextname.ToLower() == "docx" || fileextname.ToLower() == "doc" || fileextname.ToLower() == "xlsx" || fileextname.ToLower() == "xls" || fileextname.ToLower() == "ppt" || fileextname.ToLower() == "pptx" || fileextname.ToLower() == "pdf")
                        {

                        }
                        else
                        {
                            ErrorStr += filename + "文档类型错误！，";
                            continue;
                        }
                    }

                    //判断文件类型是否符合要求
                    if (!string.IsNullOrEmpty(filename))
                    {
                        //限定上传文件大小
                        if (MaxFileSize >= filesize)
                        {
                            if (attachSave == 1) sSaveDir = DateTime.Now.ToString("yyyy") + DateTime.Now.ToString("MM") + DateTime.Now.ToString("dd");
                            if (attachSave == 2) sSaveDir = DateTime.Now.ToString("yyyy") + DateTime.Now.ToString("MM");

                            if (!string.IsNullOrEmpty(sSaveDir)) sSaveDir += "\\";
                            if (!Directory.Exists(UploadDir + sSaveDir)) CommUtils.CreateDir(UploadDir + sSaveDir);   // 如果指定目录不存在则建立

                            //根据年月日时分秒+随机数产生新文件名
                            long tick = DateTime.Now.Ticks;
                            Random random = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32));
                            string newFileName = FileNamePrefix + DateTime.Now.ToString("dd") + DateTime.Now.ToString("hh") + DateTime.Now.ToString("mm") + DateTime.Now.ToString("ss") + random.Next(1000, 9999).ToString() + "." + fileextname;
                            try
                            {
                                HttpContext.Current.Request.Files[i].SaveAs(UploadDir + sSaveDir + newFileName);
                                SuccessStr += filename + ",";
                                sFileName += newFileName + ",";
                                AFileSize += filesize + ",";
                                result = true;
                            }
                            catch
                            {
                                ErrorStr += filename + "未知错误，";
                            }

                        }
                        else
                        {
                            ErrorStr += filename + "文档过大，";
                        }
                    }
                }
            }
            return result;
        }

        #endregion

        public static string GetFileImg(string sFileType)
        {
            switch (sFileType.ToLower())
            {
                case "word":
                    return "";
                case "excel":
                    return "";
                case "ppt":
                    return "";
            }
            return "";
        }
    }
}
